package sudoku.model;

import sudoku.data.ChoiceButton;
import sudoku.util.Config;

public class ChoiceModel {

	private volatile Config config;
	private volatile SudokuModel model;
	private ChoiceButton choiceButton[];
	private int valik_i;

	public ChoiceModel(Config config, SudokuModel model) {
		this.config = config;
		this.model = model;
	}

	public void arvutiAbi() {
		for (int i = 0; i < config.getRuudustik(); i++) {
			try {
				if (model.getSudokuButtons()[model.getValik_i()][i].isAbiNupp())
					model.getSudokuButtons()[model.getValik_i()][i].setNumber(" ");
				int a = Integer.parseInt(model.getSudokuButtons()[model.getValik_i()][i].getNumber());
				choiceButton[a].setKasEksisteerib(false);
			} catch (Exception exception) {
			}
			try {
				if (model.getSudokuButtons()[i][model.getValik_j()].isAbiNupp())
					model.getSudokuButtons()[i][model.getValik_j()].setNumber(" ");
				int a = Integer.parseInt(model.getSudokuButtons()[i][model.getValik_j()].getNumber());
				choiceButton[a].setKasEksisteerib(false);
			} catch (Exception exception1) {
			}
		}

		int rida = 0;
		int veerg = 0;
		if (model.getValik_i() > config.getKast() - 1 && model.getValik_i() < config.getKast() * 2)
			rida = config.getKast();
		if (model.getValik_i() > config.getKast() * 2 - 1 && model.getValik_i() < config.getKast() * 3)
			rida = config.getKast() * 2;
		if (model.getValik_i() > config.getKast() * 3 - 1 && model.getValik_i() < config.getKast() * 4)
			rida = config.getKast() * 3;
		if (model.getValik_j() > config.getKast() - 1 && model.getValik_j() < config.getKast() * 2)
			veerg = config.getKast();
		if (model.getValik_j() > config.getKast() * 2 - 1 && model.getValik_j() < config.getKast() * 3)
			veerg = config.getKast() * 2;
		if (model.getValik_j() > config.getKast() * 3 - 1 && model.getValik_j() < config.getKast() * 4)
			veerg = config.getKast() * 3;
		for (int i = rida; i < rida + config.getKast(); i++) {
			for (int j = veerg; j < veerg + config.getKast(); j++)
				try {
					int a = Integer.parseInt(model.getSudokuButtons()[i][j].getNumber());
					choiceButton[a].setKasEksisteerib(false);
				} catch (Exception exception2) {
				}

		}

	}

	public ChoiceButton[] getChoiceButton() {
		return choiceButton;
	}

	public int getValik_i() {
		return valik_i;
	}

	public void setValik_i(int valik_i) {
		this.valik_i = valik_i;
	}

	public void uusModel() {
		choiceButton = new ChoiceButton[config.getRuudustik() + 1];
		for (int i = 0; i < choiceButton.length; i++) {
			choiceButton[i] = new ChoiceButton(config.getLahendus());
			if (i != 0)
				choiceButton[i].setNumber(String.valueOf(i));
		}

		if (config.isComputerchoice()) {
			arvutiAbi();
			for (int i = 0; i < choiceButton.length; i++)
				if (!choiceButton[i].isKasEksisteerib())
					choiceButton[i].setV2rv(config.getEsialgne());

		}
	}
}